/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
 */

$(document).ready(function () {
    var $input = $('input[type="checkbox"],input[type=radio]');
    $input.iCheck({
        checkboxClass: 'icheckbox_minimal-blue',
        radioClass   : 'iradio_minimal-blue',
        increaseArea : '20%' // optional
    });
    var sel = {
        error_p      : 'p.error',
        error_message: '<p class="error">此题是必答题</p>'
    };
    var eles = {
        '$qitem': $('div.qItem')
    };
    eles.$qitem.on('click', 'li', function (e) {
        var data = $(this).data();
        var $2 = $('input[name=' + data.name + '][value=' + data.data + ']');
        $2.prop('checked', 'checked');
        $input.iCheck('update');
    });

    $('#submit_vote').on('click', function (e) {
        eles.$qitem.removeClass('qBd');
        eles.$qitem.find(sel.error_p).remove();
        var $categorys = $('ul[data-category]');
        var category_length = $categorys.length;
        var first = true;
        var hasError = false;
        if (category_length > 0) {
            var choose_val = [];
            for (var i = 0; i < category_length; i++) {
                var vote_category = $categorys[i];
                var category = $(vote_category).attr('data-category');
                var choose_vals  = [];
                $('input[name=' + category + ']:checked').each(function() {
                    choose_vals.push($(this).val());
                });
                if (choose_vals.length > 0) {
                    choose_val.push(category + '|' + choose_vals.join('-'));
                } else {
                    hasError = true;
                    var $voteItem = $('#vote_item_' + category);
                    if (first) {
                        $('html,body').animate({scrollTop: $voteItem.offset().top}, 800);
                    }
                    first = false;
                    $voteItem.addClass('qBd');
                    $voteItem.append(sel.error_message);
                    return;
                }
            }
            if (!hasError) {
                var $this = $(this);
                $.post($this.attr('data-url'), {'DATA': choose_val.join(','), 'mid': po.member, 'wxno': po.wx_no, 'set': po.set}, function (rst) {
                    if (rst.status == 'OK') {
                        window.location.href = $this.attr('data-ok')
                    } else {

                    }
                });
            }
        }
    });

    //{'member':1,'wx_no':'xxxx','chooses':'1|1,2|1-2-2,3|1'}
    // 1|2-3: 1表示问题ID，2-3表示选项索引
});